import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param listMap
 * @param route
 */
function hasPermission(listMap, route) {
  const path = route.path
  // 报表是动态的特使处理一下
  const allowPath = ['/ss-fhb/report/index/:id', '/layout']
  if (Array.isArray(listMap(path)) || allowPath.indexOf(path) >= 0) {
    return true
  }
  return false
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param listMap
 */
function _filterAsyncRouter(asyncRouterMap, listMap) {
  const accessedRouters = asyncRouterMap.map(route => {
    if (Array.isArray(route.children)) {
      route.children = route.children.filter(v => {
        return hasPermission(listMap, v)
      })
    }
    return route
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        //  listMap 后端菜单树
        const {listMap} = data
        commit('SET_ROUTERS', _filterAsyncRouter(asyncRouterMap, listMap))
        resolve()
      })
    }
  }
}

export default permission
